package cn.uce.common.redis.support;

import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.util.Assert;

import java.util.Set;

import static org.apache.http.util.Asserts.notNull;
import static org.springframework.util.Assert.isTrue;
import static org.springframework.util.StringUtils.commaDelimitedListToSet;
import static org.springframework.util.StringUtils.split;

/** 支持哨兵模式配置
 * @author Sunny
 */
public class RedisConfiguration extends RedisSentinelConfiguration {

    private String nodes;

    public RedisConfiguration(){

    }

    public RedisConfiguration(Iterable<RedisNode> sentinels){
        notNull(sentinels, "Cannot set sentinels to 'null'.");
        Set<RedisNode> sentinels2 = getSentinels();
        if(!sentinels2.isEmpty()){
            sentinels2.clear();
        }

        for (RedisNode sentinel : sentinels) {
            addSentinel(sentinel);
        }
    }

    public void setNodes(String nodes) {
        notNull(nodes, "Cannot set redis.sentinel.nodes to 'null'.");
        this.nodes = nodes;
        appendSentinels(commaDelimitedListToSet(nodes));
    }

    private void appendSentinels(Set<String> hostAndPorts) {

        for (String hostAndPort : hostAndPorts) {
            addSentinel(readHostAndPortFromString(hostAndPort));
        }
    }

    private RedisNode readHostAndPortFromString(String hostAndPort) {

        String[] args = split(hostAndPort, ":");

        Assert.notNull(args, "HostAndPort need to be seperated by  ':'.");
        isTrue(args.length == 2, "Host and Port String needs to specified a s host:port");
        return new RedisNode(args[0], Integer.valueOf(args[1]).intValue());
    }
}
